import { ElMessageBox, ElMessage } from 'element-plus';
import { msgError,msgSuccess,msg18n,msgWarning,msgInfo } from '@/utils';
import { apiUrl ,ActionKey, ModuleKey } from '@/api/apiUrl';
import { get, post, put, httpDelete } from '@/utils/request'; // 绝对路径
import type { FormSaveOptions, SaveResult } from '@/types';
import { $t } from '@/locales'


/**=======删除======== */

/* ===== 1. 通用提示 ===== */
const tip = {
  empty: $t('table.noSelected'),
  reason: $t('message.deleteReasonNoNull'),
  success: $t('message.opSuccessful'),
  cancel : $t('message.opCanceled'),
  duplicates: $t('message.saveDuplicates'),
};

/* ===== 2. 删除（支持软删/硬删） ===== */
export async function remove(
  module: ModuleKey,
  action: 'delete' | 'mark',
  rows: Record<string, any>[],
  pk = 'id'
): Promise<void> {
  if (!rows.length) {
     msgWarning(tip.empty);
    return [];
    
    };
  /* ① 防御：保证一定是数组 */
  const dataList = Array.isArray(rows) ? rows : [rows];

  const len = dataList.length;
  const actionTxt = action === 'mark' ? $t('message.confirmMarkTitle') : $t('message.confirmDeleteTitle');

  /* ① delete 专属：二次确认 */
  if (action === 'delete') {
    await ElMessageBox.confirm(
      $t('message.deleteInputReasonTitle',{len:len}),
      $t('message.warning'),
      { confirmButtonText: $t('btn.confirm'), cancelButtonText: $t('btn.cancel'), type: 'warning' }
    ).catch(() => {
      msgInfo(tip.cancel);
      throw 'cancel';
    });
  }

  /* ② mark 专属：直接填原因（无前置确认） */
  let reason = '';
  if (action === 'mark') {
    reason = await ElMessageBox.prompt(
      $t('message.markInputReasonTitle',{len:len}),
      $t('message.deleteReason'),
      {
        confirmButtonText: $t('message.confirm'),   // ← 确认
        cancelButtonText:  $t('message.cancel'),    // ← 取消
        inputPattern: /^\s*\S{1,}\s*$/,
        inputErrorMessage: tip.reason,
      }
    ).then(({ value }) => value.trim()).catch(() => {
      msgInfo(tip.cancel);
      throw 'cancel';
    });
  }

  /* ③ 调接口 */
  const body = dataList.map(r => ({
    deletion_model: action,
    pk_names: [pk],
    pk_values: [String(r[pk])],
    deletion_reason: reason,
    data: {},
  }));
  console.log('body',body)
  const apiPath=apiUrl.url(module, 'delete')
  console.log('apiPath',apiPath)
  const result = await httpDelete(apiUrl.url(module, action), body);
  console.log('result', result);
  msgSuccess(tip.success)
   
  return result
}


/* ===== 3. 新增（单条 | 批量） ===== */
export async function create(
  module: ModuleKey,
  data: any | any[], // 单条对象 或 数组
  action: 'insert' | 'insertBatch' = Array.isArray(data) ? 'insertBatch' : 'insert'
) {
 
  const result = await  post(apiUrl.url(module, action), data);
   
  return result.data
  
}

/* ===== 4. 修改（单条 | 批量） ===== */
export async function edit(
  module: ModuleKey,
  data: any | any[],
  action: 'updateById' | 'update' = Array.isArray(data) ? 'update' : 'updateById',
  id?: string | number // 单条时必须
) {
  const url = action === 'updateById' ? apiUrl.url(module, action, id) : apiUrl.url(module, action);
 const result = await put(url, data);
  msgSuccess(tip.success);
  return result.data;
}

/* ===== 5. 查询（分页 | 单条 | 条件） ===== */
export async function query(
  module: ModuleKey,
  action: 'select' | 'selectById' | 'selectQuery',
  params?: any, // 查询条件或 id
  id?: string | number
) {

  console.log('params1',params)
  if (action === 'selectQuery')  
    action = 'select';
  else if (action === 'select') 
    action = 'selectQuery';
  if (action === 'selectById' && id === undefined) 
    {
          const msg = $t('message.fieldRequired', { field: 'ID' });
          throw new Error(msg);
    }
  const url = action === 'selectById' ? apiUrl.url(module, action, id) : apiUrl.url(module, action);
  console.log('url',url)
  console.log('params',params)
  let result: any;
  if (action === 'selectQuery')
     result = await post(url,params);
  else
     result = await get(url,params);
  return result.data //request.get(url,  {} ).then(res => res.data);
}


/* ===== 6. 通用 新增/编辑 保存（带表单校验 & 自动区分 insert/update） ===== */
/*
export interface FormSaveOptions<T = any> {
  module: ModuleKey;
  formData: T;
  formRef?: any;          // el-form 的 ref，可选
  isUpdate?: boolean;     // 强制指定走 update；不传则按 id 判断
}

export interface SaveResult<T = any> {
  success: boolean;
  data?: T;               // 后端返回的单条记录
  msg?: string;
}
  */

export async function doFormSave<T extends Record<string, any>>(
  opts: FormSaveOptions<T>
): Promise<SaveResult<T>> {
  const { module, formData, formRef, isUpdate } = opts;
  /* 0. 深拷贝转纯对象（去掉 Proxy、类实例、undefined 等）*/
  const pureData = JSON.parse(JSON.stringify(formData)) as T;
  /* 1. 表单校验（可选） */
if (formRef) {
  const valid = await formRef.validate().catch(() => false);
  if (!valid) {
    return { success: false, msg: $t('message.formValidateFailed') };
  }
}

  /* 2. 区分 insert / update */
  const updateFlag = isUpdate ?? (pureData.id !== undefined);
  console.log('doFormSave.pureData',pureData)
  try {
    let res: any;
    if (updateFlag) {
      res = await edit(module, pureData, 'updateById', pureData.id);
    } else {
      res = await create(module, pureData);   // 走 insert/insertBatch
    }

    /* 3. 取后端返回的单条数据（兼容你之前的结构） */
    let row: T | undefined;
    if (updateFlag) {
      row = Array.isArray(res) ? res[0] : res;
      
    } else {
      if (res.created?.count > 0) 
        {
          row = res.created.details[0];
         msgSuccess(tip.success);
        }
      else if (res.duplicates?.count > 0) 
        {
          
          row = res.duplicates.details[0];
          msgError(tip.duplicates);
        }
    }

    return { success: true, data: row };
  } catch (e: any) {
    // 统一弹错（create/edit 里已经弹过，这里可再补一句）
     
    return { success: false, msg: e.message };
  }
}

/* ---------- 以下是系统管理专用接口 ---------- */
// 权限接口 增加data
export const getPerms = async (data: any) => {
  try {
    
    const result = await get('/permission',data); // 使用封装的 get 方法
    // console.log('result',result);
    // console.log('result data',result.data );
    return result.data  ;// result.data  为了返回值统一，增加data
  } catch (error) {
    console.error('获取权限数据失败:', error);
    return [];
  }
};

 // 字段接口 
export const getFields = async (alias: string) => {
  try {
    const { data } = await get('/fields', { alias } );
    return { data: data ?? [] };          // 始终有 data 字段
  } catch (e) {
    console.error('获取字段数据失败:', e);
    return { data: [] };                  // 同构兜底
  }
};

// 菜单接口 增加data
export const getMenu = async (data: any) => {
  try {
    
    const result = await get('/menu',data); // 使用封装的 get 方法
    // console.log('result',result);
    // console.log('result data',result.data );
    return result.data  ;// result.data  为了返回值统一，增加data
  } catch (error) {
    console.error('获取菜单数据失败:', error);
    return [];
  }
};
